<?php

namespace Frieza\Modules\Circle\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\Circle\CircleActiveTag;
use Doraemon\cache\Queue;
use Doraemon\model\Circle\CircleBaseInfo;
use Doraemon\model\Circle\CircleOperationLog as mCircleOperationLog;
use Doraemon\model\Circle\PhotosCircle;
use Doraemon\model\Member;
use Doraemon\pockets\datebase\BaseDbModel;
use Doraemon\service\Circle\CircleOperationLog as sCircleOperationLog;
use Doraemon\service\es\EsPhoto;
use Doraemon\service\Photos as sPhotos;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Frieza\Modules\Circle\Extensions\CarryButton;
use Illuminate\Http\Request;
use mysql_xdevapi\Exception;
use Doraemon\service\Circle\PhotosCircle as sPhotosCircle;
use Doraemon\cache\Circle\CircleContentCounter;
use Doraemon\service\MothersDay\BlessConfig;

class PhotosCircleController extends Controller
{
    //内容管理
    public function index(Content $content, Request $request): Content
    {
        //圈子信息
        $circleName = CircleBaseInfo::getNameId();
        $params = $request->all();
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];

        try {
            $res = PhotosCircle::getList($params, $limit);
            $photos = sPhotosCircle::getListInfo($res['rows']);
            foreach ($photos as $key => $val) {
                $photos[$key]['expand'] = $this->getPicExpand(['pics' => $val['images']]) . $this->_getDivLine();
                $photos[$key]['circle_name'] = $circleName[$val['circle_id']];
                $photos[$key]['photo']['remark'] = $this->highLight($val['photo']['remark']);
            }
        } catch (Exception $exception) {
            $photos = [];
            $res['total'] = 0;
        }

        $gridModel = new pGridDataModel($photos, $res['total'], [
            'perPage' => $pageSize,
            'keyName' => 'photo_id'
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($circleName) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();

            $grid->tools(function (Grid\Tools $tools) {
                $tools->append(new CarryButton);
            });

            $grid->filter(function (Grid\Filter $filter) use ($circleName) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1 / 2, function ($filter) use ($circleName) {
                    $filter->between('release_time', '发布时间')->date();
                    $filter->equal('circle_id', '圈子名称:')->select($circleName);
                    $filter->in('is_top', '是否置顶:')->radio([1 => '是', 0 => '否']);
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('photos_id', '内容id:');
                    $filter->in('is_best', '是否加精:')->radio([1 => '是', 0 => '否']);
                });
            });

            $grid->column('circle_name', '所属圈子')->expand(function () {
                return $this->expand;
            }, true);
            $grid->column('photo', '内容信息')->width(500)->display(function ($released) {
                $remark = $released['remark'];
                return "<strong>[id]：</strong>{$released['photo_id']}<br><strong>[标题]：</strong>
                    {$released['title']}<br><strong>[正文]：</strong>{$remark}";
            });

            $grid->column('add_time', '发布时间');
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);

            $grid->column('counter', '交互情况')->width(100)->display(function ($counter) {
                $photoId = $this->photo['photo_id'];
                $url = "/admin/comment/index?search[obj_id]={$photoId}";
                return "赞：{$counter['like']} <br/> 评论：<a href='{$url}' target='_blank'>{$counter['comments']}</a> <br/> 收藏：{$counter['favorite']}  <br/> 分享：{$counter['share']} ";
            });
            Admin::script($this->setScript());
            $grid->actions(function ($actions) {
                $actions->row->setKeyName('id');
                $actions->disableDelete();
                // 去掉编辑
                $actions->disableEdit();
                // 去掉查看
                $actions->disableView();

//                $best = $actions->row->is_best == 1 ? '取消加精' : '加精';
//                $isBest = $actions->row->is_best == 1 ? 0 : 1;
                $top = $actions->row->is_top == 1 ? '取消置顶' : '置顶';
                $isTop = $actions->row->is_top == 1 ? 0 : 1;
                $judgmentBasis = PhotosCircleController::judgmentBasis($actions->row->show_status);
                $actions->prepend('<p><a class="setHide label  label-info" data-id="' . $actions->row->id . '" data-show-status="' . $judgmentBasis['show_status']['value'] . '" data-uid="' . $actions->row->uid . '" href="javascript:void(0);">' . $judgmentBasis['show_status']['desc'] . '</a></p>');
                $actions->prepend('<p><a class="setTop label  label-info" data-id="' . $actions->row->id . '"  data-best="' . $isTop . '" data-circle_id="' . $actions->row->circle_id . '" href="javascript:void(0);">' . $top . '</a></p>');
//                $actions->prepend('<p><a class="setBest label  label-info" data-id="' . $actions->row->id . '" data-best="' . $isBest . '" href="javascript:void(0);">' . $best . '</a></p>');
            });
        });
        Admin::script($this->imgScript());
        return $content
            ->header('内容管理')
            ->breadcrumb(['text' => '内容管理', 'url' => '/admin/circle/photos/list'])
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>")
            ->body($listGrid);
    }

    /**
     * @return string
     */
    private function setScript()
    {
        return <<<SCRIPT
         $('.setBest').unbind('click').click(function(){
            var id= $(this).attr('data-id');
            var is_best = $(this).attr('data-best');
            let that = $(this)
            let url = '/admin/circle/photos/operation/'+ id;
            let params = {
                is_best:is_best
            };
            $.post(url, params , function (result) {
                if (result.status == 1) {
                    that.attr('data-best',is_best == 1?'0':'1')
                    that.text(is_best == 1?'取消加精':'加精')
                    layer.msg(result.message);
                } else {
                    layer.msg(result.message);
                }
            });
        });
        $('.setTop').unbind('click').click(function(){
            var id= $(this).attr('data-id');
            var is_top = $(this).attr('data-best');
            var circle_id = $(this).attr('data-circle_id');
            let that = $(this)
            let url = '/admin/circle/photos/operation/'+ id;
            let params = {
                is_top:is_top,
                circle_id:circle_id,
            };
            $.post(url, params , function (result) {                
                if (result.status == 1) {
                    that.attr('data-best',is_top == 1?'0':'1')
                    that.text(is_top == 1?'取消置顶':'置顶')
                    layer.msg(result.message);                                
                } else {
                    layer.msg(result.message);
                }
            });
        });
         $('.setHide').unbind('click').click(function() {
            var id = $(this).attr('data-id');
            var show_status = $(this).attr('data-show-status');
            var uid = $(this).attr('data-uid');
            var that = $(this)
            console.log(that);
            let url = '/admin/circle/photos/show-status/'+ id;
            let params = {
                show_status:show_status,
                uid:uid
            };
            var title = show_status == 1?'取消折叠':'折叠'
            swal({
                title: "确定"+title+"该内容？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                   $.post(url, params , function (result) {              
                         if (result.status == 1){
                            that.attr('data-show-status',show_status == 1?0:1)
                            that.text(show_status == 1?'折叠':'取消折叠')
                            layer.msg(result.message);                              
                        } else {
                            layer.msg(result.message);
                        }
                    });
                }
            });
            
        });
        SCRIPT;
    }


    private function getPicExpand($picArr)
    {
        $row = new Row();
        if ($picArr['pics']) {
            $GirdModel = new pGridDataModel($picArr, null, ['pageName' => '']);
            $grid = new Grid($GirdModel);
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disableTools();
            $grid->disableActions();
            $grid->disableExport();
            $grid->column('pic', 'pic信息')->display(function () {
                $infos = json_decode($this, true);
                if ($infos && is_array($infos)) {
                    $pic = '';
                    foreach ($infos as $picInfo) {
                        if ($picInfo['is_video']) {
                            $pic .= "<div style='display:inline-block;margin:10px;height:220px;'>" .
                                "<video src='" . $picInfo['pic_url'] . "' height='300px' controls /></video>" .
                                "<br>" . $picInfo['pic_id'] . "</div>";
                        } else {
                            $pic .= "<div style='display:inline-block;margin:10px;height:220px;'>" .
                                "<img src='" . $picInfo['pic_url'] . "' height='200px' class='imgss' />" .
                                "<br>" . $picInfo['pic_id'] . "</div>";
                        }
                    }
                    return $pic;
                }
            });

            $grid->disablePagination();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->disableView();
            });
            $row->column('12', $grid);
            return $row->render();
        }
        return '';
    }

    public function imgScript(): string
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.imgss').click(function() {
          
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });
SCRIPT;
    }

    /**
     * 分割线
     * @return string
     */
    private static function _getDivLine(): string
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }

    /**
     * 置顶、加精
     *
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function operation($id, Request $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->only(['is_best', 'is_top', 'circle_id']);
        $result = ['status' => 0, 'message' => '操作失败'];
        //todo 查询绑定信息
        $info = PhotosCircle::get('*', ['id' => $id]);
        if (isset($data['is_top']) && $data['is_top'] == 1) {//置顶的操作
            //判断次数限制
            $where = [
                'circle_id' => $data['circle_id'],
                'bind_status' => BaseDbModel::STATUS_NORMAL,
                'is_top' => 1
            ];
            $count = PhotosCircle::count($where);
            if ($count >= 10) {
                $result = ['status' => 0, 'message' => '同一圈子最多支持置顶 10 条内容'];
                return response()->json($result);
            }
        }
        $data['photos_id'] = $info['photos_id'];
        $data['circle_id'] = $info['circle_id'];

        //备注
        $setType = isset($data['is_top']) ? '置顶' : '加精';
        $setValue = ($data['is_top'] ?? 0 || $data['is_best'] ?? 0) ? '' : '取消';
        $oper_remark = '后台执行' . $setValue . $setType . '操作';

        $upd = sPhotosCircle::updatePhotoCircle(
            $id,
            $data,
            PhotosCircle::JOIN_CHANNEL_ADMIN,
            Admin::user()->id,
            $oper_remark
        );

        if (!empty($upd)) {
            //圈子事件操作记录---加精取消加精
            if (isset($data['is_best'])) {
                $event = 0 == $data['is_best'] ? mCircleOperationLog::CIRCLE_NOT_BEST : mCircleOperationLog::CIRCLE_BEST;
            } else {
                $event = 0 == $data['is_top'] ? mCircleOperationLog::CIRCLE_NOT_TOP : mCircleOperationLog::CIRCLE_TOP;
            }
            sCircleOperationLog::addLog($data['circle_id'], $data['photos_id'], $event, Admin::user()->id, mCircleOperationLog::SOURCE_ADMIN);
            if ($data['is_best'] == PhotosCircle::IS_BEST) {
                // 发通知
                $member = Member::getOne($info['uid']);
                $circleBaseInfo = CircleBaseInfo::getInfo(['circle_id' => $info['circle_id']]);
                // $photosInfo = sPhotos::getPhoto($info['photos_id']);
                Queue::insertQueue('queue/Sysmsg/Send', [
                    'msgCode' => 733,
                    'to_uid' => $info['uid'],
                    'msgParams' => [
                        'nickName' => $member['nick'],
                        'circleName' => $circleBaseInfo['circle_name'],
                        'photoId' => urlencode(base64_encode(json_encode(['id' => $info['photos_id']]))),
                        //'img' => $photosInfo['pic_url'] ? : "https://img.haohaozhu.cn/Op-imageShow/b0a7e20ku0af0TN00rau5ly?iv=1"
                    ]
                ], Queue::QUEUE_DORAEMON);
            }
            $result = ['status' => 1, 'message' => '操作成功'];
        }

        //todo 积福--圈子加精
//        if (isset($data['is_best'])) {
//            $eventName = (1 == $data['is_best']) ? BlessConfig::BLESS_PHOTOS_CIRCLE_GOODS : BlessConfig::BLESS_PHOTOS_CIRCLE_NOT_GOODS;
//            \Doraemon\amqp\CommunityQueue::insertQueue(\Doraemon\service\MothersDay\BlessConfig::MQ_NAME, [
//                'event_name' => $eventName,
//                'obj_id' => $info['photos_id'],
//                'uid' => $info['uid']
//            ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);
//        }

        return response()->json($result);
    }

    public static function judgmentBasis($showStatus): array
    {
        $result['show_status']['value'] = PhotosCircle::SHOW_STATUS_NORMAL;
        $result['show_status']['desc'] = '取消折叠';
        if ($showStatus == PhotosCircle::SHOW_STATUS_NORMAL) {
            $result['show_status']['value'] = PhotosCircle::SHOW_STATUS_HIDDEN;
            $result['show_status']['desc'] = '折叠';
        }
        return $result;
    }

    public function showStatus($id, Request $request): \Illuminate\Http\JsonResponse
    {
        $info = PhotosCircle::get('*', ['id' => $id]);
        $showStatus = $request->get('show_status');
        $uid = $request->get('uid');
        if (empty($uid) || empty($info)) {
            $result = ['code' => 0, 'message' => '圈子信息查找不到,请刷新重试'];
            return response()->json($result);
        }
        $circleId = $info['circle_id'];
        $addTime = $info['addtime'];
        $photosId = $info['photos_id'];
        $behavior = $showStatus == 1 ? '取消折叠' : '折叠';
        $operRemark = '后台执行 ' . $behavior . '操作';
        $data['show_status'] = $showStatus;
        $upd = sPhotosCircle::updatePhotoCircle(
            $id,
            $data,
            PhotosCircle::JOIN_CHANNEL_ADMIN,
            Admin::user()->id,
            $operRemark
        );
        if (empty($upd)) {
            $result = ['code' => 0, 'message' => '操作失败,请重试'];
            return response()->json($result);
        }
        //圈子事件操作记录---折叠取消折叠
        $event = 0 == $showStatus ? mCircleOperationLog::CIRCLE_HIDDEN : mCircleOperationLog::CIRCLE_NOT_HIDDEN;
        sCircleOperationLog::addLog($circleId, $photosId, $event, Admin::user()->id, mCircleOperationLog::SOURCE_ADMIN);

        if ($showStatus == 0) {
            //todo 先手动同步es
            $result['circle_show_status'] = 0;
            EsPhoto::post($info['photos_id'], $result);
            //对应后端统计的圈子内容计数 -1
            CircleContentCounter::decrTotal($circleId);
            //该账号用于计算圈子活跃标签的内容数-1
            CircleActiveTag::delInfo($circleId, $uid, $photosId);

            //自动触发针对该用户的下行通知
            $nickName = \Doraemon\model\Member::getNickByUid($uid);
            $circleName = CircleBaseInfo::getInfo(['circle_id' => $circleId], 'circle_name');
            if ($uid) {
                $a = Queue::insertQueue('queue/Sysmsg/Send', [
                    'msgCode' => 719,
                    'to_uid' => $uid,
                    'msgParams' => [
                        'nickName' => $nickName,
                        'circleName' => $circleName,
                        'link' => HhzNiceLivingUrl::getNoteDetailLink($info['photos_id'])
                    ]
                ], Queue::QUEUE_DORAEMON);
                Log::debug('压入队列', [$a]);
            }
        } else {
            //后端统计的圈子内容计数 +1
            CircleContentCounter::incrTotal($circleId);
            //该账号用于计算圈子活跃标签的内容数+1
            if ((time() - $addTime) < 7 * 86400) {
                CircleActiveTag::setInfo($circleId, $uid, [$photosId => ['obj_id' => $photosId, 'time' => (int)$addTime]]);
            }
            //todo 先手动同步es
            $result['circle_show_status'] = 1;
            EsPhoto::post($info['photos_id'], $result);
        }
        //todo 积福--圈子折叠
//        $eventName = (1 == $showStatus) ? BlessConfig::BLESS_PHOTOS_CIRCLE_SHOW : BlessConfig::BLESS_PHOTOS_CIRCLE_NOT_SHOW;
//        \Doraemon\amqp\CommunityQueue::insertQueue(BlessConfig::MQ_NAME, [
//            'event_name' => $eventName,
//            'obj_id' => $info['photos_id'],
//            'uid' => $uid
//        ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);

        $result = ['status' => 1, 'message' => '操作成功'];
        return response()->json($result);
    }

    // 正文中轻话题高亮
    private function highLight($remark)
    {
        preg_match_all('/#([\w\-]{1,15}+)/u', $remark . ' ', $userTags);

        if (isset($userTags[0]) && !empty($userTags[0])) {
            $replaceRemarkArr = [];
            foreach ($userTags[0] as $userTag) {
                $replaceRemarkArr[] = '<b style="color:deepskyblue;">' . $userTag . '</b>';
            }
            return str_replace($userTags[0], $replaceRemarkArr, $remark);
        }

        return $remark;
    }
}